/*
 * Created on Feb 13, 2005
 * Created by dfhuynh
 */
package edu.mit.simile.longwell.query.compare;

import com.hp.hpl.jena.rdf.model.Literal;
import com.hp.hpl.jena.rdf.model.Resource;

import edu.mit.simile.longwell.Profile;

/**
 * @author dfhuynh
 */
public class StringComparator extends ComparatorBase {
	final protected boolean m_caseSensitive;
	
	/**
	 * @param profile
	 * @param parameter
	 * @param locale
	 */
	public StringComparator(Profile profile, String parameter) {
		super(profile, parameter);
		m_caseSensitive = "c".equals(parameter);
	}
	
	/* (non-Javadoc)
	 * @see edu.mit.simile.longwell.query.compare.IComparator#preprocess(java.lang.Object, java.lang.String)
	 */
	public Object preprocess(Object value, String locale) {
		return objectToString(value, locale);
	}

	/* (non-Javadoc)
	 * @see edu.mit.simile.longwell.query.compare.ComparatorBase#internalCompareAscending(java.lang.Object, java.lang.Object, java.lang.String)
	 */
	protected int internalCompareAscending(Object v1, Object v2, String locale) {
		// TODO Use a collator here: Collator.getInstance(getLocale(locale)).compare(...)
		String s1 = v1 == null ? "" : (String) v1;
		String s2 = v2 == null ? "" : (String) v2;
			
		if (m_caseSensitive) {
			return s1.compareTo(s2);
		} else {
			return s1.compareToIgnoreCase(s2);
		}
	}

	protected String objectToString(Object v, String locale) {
		String s = null;
		if (v instanceof Literal) {
			s = ((Literal) v).getString();
		} else if (v instanceof Resource) {
			s = m_profile.getSchemaModel().getLabel((Resource) v, locale, true);
		} else if (v != null) {
			s = v.toString();
		}
		
		if (s == null) {
			s = "";
		}
		return s;
	}
}
